//
//  UserAccount.swift
//  HyWeibo
//
//  Created by HY-Mac on 16/7/1.
//  Copyright © 2016年 HY-Mac. All rights reserved.
//

import UIKit

class UserAccount: NSObject,NSCoding {
    //用于调用access_token，接口获取授权后的access token。
    var access_token: String?
    //access_token的生命周期，单位是秒数
    var expires_in: NSTimeInterval = 0{
        didSet{
            expires_date = NSDate(timeIntervalSinceNow: expires_in)
        }
        
    }
    //当前授权用户的UID
    var uid: String?
    
    //用户头像地址 String
    var avatar_large: String?
    //用户名
    var name: String?
    //
    var expires_date: NSDate?
    /// 用户昵称
    var screen_name: String?
    
    //KVC设置初始值
    init(dict: [String: AnyObject]) {
        super.init()
        setValuesForKeysWithDictionary(dict)
    }
    //必须重写这个方法，否则会为所有字段赋值模型
    override func setValue(value: AnyObject?, forUndefinedKey key: String) {
        
    }
    override var description: String{
        let keys = ["access_token","expires_in","uid","avatar_large","name","expires_date"]
        return dictionaryWithValuesForKeys(keys).description
    }
    func saveUserAccount(){
        let path = (NSSearchPathForDirectoriesInDomains(.DocumentDirectory, .UserDomainMask, true).last! as NSString).stringByAppendingPathComponent("userAccount.plist")
        NSKeyedArchiver.archiveRootObject(self, toFile: path)
        print(path)
    }
    class func loadUserAccount() -> UserAccount?{
        let path = (NSSearchPathForDirectoriesInDomains(.DocumentDirectory, .UserDomainMask, true).last! as NSString).stringByAppendingPathComponent("userAccount.plist")
        if let account = NSKeyedUnarchiver.unarchiveObjectWithFile(path) as? UserAccount{
            if account.expires_date?.compare(NSDate()) == NSComparisonResult.OrderedDescending{
                return account
            }
        }
        return nil
    }
    
    //MARK:实现归档方法
    required init?(coder aDecoder: NSCoder) {
        access_token = aDecoder.decodeObjectForKey("access_token") as? String
        expires_in = aDecoder.decodeDoubleForKey("expires_in")
        uid = aDecoder.decodeObjectForKey("uid") as? String
        avatar_large = aDecoder.decodeObjectForKey("avatar_large") as? String
        name = aDecoder.decodeObjectForKey("name") as? String
        expires_date = aDecoder.decodeObjectForKey("expires_date") as? NSDate
        self.screen_name = aDecoder.decodeObjectForKey("screen_name") as? String
        
    }
    func encodeWithCoder(aCoder: NSCoder) {
        aCoder.encodeObject(access_token, forKey: "access_token")
        aCoder.encodeDouble(expires_in, forKey: "expires_in")
        aCoder.encodeObject(uid, forKey: "uid")
        aCoder.encodeObject(avatar_large, forKey: "avatar_large")
        aCoder.encodeObject(name, forKey: "name")
        aCoder.encodeObject(expires_date, forKey: "expires_date")
        aCoder.encodeObject(screen_name, forKey: "screen_name")
    }

}
